import { defineFakeRoute } from 'vite-plugin-fake-server/client';

// 用户接口定义
interface User {
  id: number;
  username: string;
  password: string;
  email?: string;
  token: string;
  avatar: string;
  permissions: string[];
}

// 模拟用户数据
const users: User[] = [
  {
    id: 1,
    username: 'admin',
    password: '123456',
    email: 'admin@example.com',
    token: 'admin-token-123456',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=admin',
    permissions: ['dashboard', 'card_manage', 'fund_manage']
  },
  {
    id: 2,
    username: 'user',
    password: '123456',
    email: 'user@example.com',
    token: 'user-token-123456',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?user',
    permissions: ['dashboard']
  }
];

export default defineFakeRoute([
  // 登录接口
  {
    url: '/api/login',
    method: 'post',
    response: ({ body }) => {
      const { username, password } = body;
      const user = users.find(u => u.username === username && u.password === password);
      
      if (user) {
        return {
          msg: '',
          status: 0,
          data: {
            token: user.token,
            userInfo: {
              id: user.id,
              username: user.username,
              avatar: user.avatar,
              permissions: user.permissions
            }
          }
        };
      } else {
        return {
          msg: '用户名或密码错误',
          status: 1
        };
      }
    }
  },

  // 注册接口
  {
    url: '/api/register',
    method: 'post',
    response: ({ body }) => {
      const { username, password, email } = body;
      
      // 检查用户名是否已存在
      if (users.some(u => u.username === username)) {
        return {
          msg: '用户名已存在',
          status: 1
        };
      }
      
      // 创建新用户
      const newUser: User = {
        id: users.length + 1,
        username,
        password,
        email,
        token: `token-${Date.now()}`,
        avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`,
        permissions: ['dashboard']
      };
      
      users.push(newUser);
      
      return {
        msg: '',
        status: 0,
        data: {
          token: newUser.token,
          userInfo: {
            id: newUser.id,
            username: newUser.username,
            avatar: newUser.avatar,
            permissions: newUser.permissions
          }
        }
      };
    }
  },

  // 忘记密码接口
  {
    url: '/api/forgot-password',
    method: 'post',
    response: ({ body }) => {
      const { username } = body;
      
      // 模拟发送重置邮件
      const user = users.find(u => u.username === username);
      
      if (user) {
        return {
          msg: '',
          status: 0,
          data: {
            message: '验证码已发送到您的邮箱'
          }
        };
      } else {
        return {
          msg: '用户不存在',
          status: 1
        };
      }
    }
  },

  // 重置密码接口
  {
    url: '/api/reset-password',
    method: 'post',
    response: ({ body }) => {
      const { username, password } = body;
      
      // 模拟重置密码
      const user = users.find(u => u.username === username);
      
      if (user) {
        user.password = password;
        return {
          msg: '',
          status: 0,
          data: {
            message: '密码重置成功'
          }
        };
      } else {
        return {
          msg: '用户不存在',
          status: 1
        };
      }
    }
  },

  // 获取用户信息接口
  {
    url: '/api/current-user',
    method: 'get',
    response: ({ headers }) => {
      const token = headers.authorization?.replace('Bearer ', '');
      const user = users.find(u => u.token === token);
      
      if (user) {
        return {
          msg: '',
          status: 0,
          data: {
            id: user.id,
            username: user.username,
            avatar: user.avatar,
            permissions: user.permissions
          }
        };
      } else {
        return {
          msg: '未授权',
          status: 1
        };
      }
    }
  },

  // 仪表盘接口
  {
    url: '/api/dashboard',
    method: 'get',
    response: ({ query }) => {
      const { _action, type } = query;
      
      if (_action === 'getData') {
        // 仪表盘数据
        return {
          msg: '',
          status: 0,
          data: {
            account: {
              balance: '1250.50',
              recharge_sum: '5000.00',
              recharge_count: 15,
              recharge_pending_sum: '750.00',
              recharge_pending_count: 3
            },
            card: {
              card_count: 8,
              card_status: {
                normal: 5,
                canceling: 1,
                cancelled: 1,
                other: 1
              },
              cardbin_list: [
                { bin: '424242', count: 3, cardScheme: 'VISA' },
                { bin: '535353', count: 2, cardScheme: 'MasterCard' },
                { bin: 'Discover', count: 1, cardScheme: 'Discover' },
                { bin: '378282', count: 2, cardScheme: 'American Express' }
              ]
            }
          }
        };
      } else if (_action === 'moneyTree') {
        // 资金树图表数据
        const xdata = type === 'week'
          ? ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          : type === 'month'
          ? ['第1周', '第2周', '第3周', '第4周']
          : ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        
        return {
          msg: '',
          status: 0,
          data: {
            xdata,
            ydata: [
              {
                i18n_key: 'recharge',
                data: type === 'week'
                  ? [120, 132, 101, 134, 90, 230, 210]
                  : type === 'month'
                  ? [1200, 1320, 1010, 1340]
                  : [12000, 13200, 10100, 13400, 9000, 23000, 21000, 18000, 15000, 17000, 19000, 21000],
                color: '#5470c6'
              },
              {
                i18n_key: 'transfer',
                data: type === 'week'
                  ? [220, 182, 191, 234, 290, 330, 310]
                  : type === 'month'
                  ? [2200, 1820, 1910, 2340]
                  : [22000, 18200, 19100, 23400, 29000, 33000, 31000, 28000, 25000, 27000, 29000, 31000],
                color: '#91cc75'
              }
            ]
          }
        };
      } else {
        // 默认返回空数据
        return {
          msg: '',
          status: 0,
          data: {}
        };
      }
    }
  },

  // 资金明细接口（带fund_manage前缀）
  {
    url: '/fund_manage/api/fund/details',
    method: 'get',
    response: ({ query }) => {
      const { page = 1, pageSize = 10, type, status } = query;
      
      const details = [
        {
          transactionId: 'TRX001',
          type: 'income',
          amount: 100.50,
          paymentMethod: '支付宝',
          status: 'success',
          transactionTime: '2024-01-15 10:30:00',
          remark: '充值成功'
        },
        {
          transactionId: 'TRX002',
          type: 'expense',
          amount: 50.00,
          paymentMethod: '微信支付',
          status: 'success',
          transactionTime: '2024-01-14 14:20:00',
          remark: '消费支出'
        },
        {
          transactionId: 'TRX003',
          type: 'income',
          amount: 200.00,
          paymentMethod: '银行卡',
          status: 'pending',
          transactionTime: '2024-01-13 09:15:00',
          remark: '转账收入'
        },
        {
          transactionId: 'TRX004',
          type: 'expense',
          amount: 30.00,
          paymentMethod: '支付宝',
          status: 'failed',
          transactionTime: '2024-01-12 16:45:00',
          remark: '支付失败'
        },
        {
          transactionId: 'TRX005',
          type: 'income',
          amount: 150.00,
          paymentMethod: '微信支付',
          status: 'success',
          transactionTime: '2024-01-11 11:20:00',
          remark: '退款收入'
        }
      ];
      
      // 根据类型和状态过滤
      let filteredDetails = details;
      if (type) {
        filteredDetails = filteredDetails.filter(detail => detail.type === type);
      }
      if (status) {
        filteredDetails = filteredDetails.filter(detail => detail.status === status);
      }
      
      const pageNum = parseInt(page as string, 10);
      const pageSizeNum = parseInt(pageSize as string, 10);
      const start = (pageNum - 1) * pageSizeNum;
      const end = start + pageSizeNum;
      const paginatedDetails = filteredDetails.slice(start, end);
      
      // 统计信息
      const statistics = {
        totalIncome: filteredDetails
          .filter(d => d.type === 'income' && d.status === 'success')
          .reduce((sum, d) => sum + d.amount, 0),
        totalExpense: filteredDetails
          .filter(d => d.type === 'expense' && d.status === 'success')
          .reduce((sum, d) => sum + d.amount, 0),
        transactionCount: filteredDetails.length
      };
      
      return {
        msg: '',
        status: 0,
        data: {
          list: paginatedDetails,
          total: filteredDetails.length,
          statistics
        }
      };
    }
  },

  // 测试接口
  {
    url: '/test-api',
    method: 'get',
    response: () => {
      return {
        msg: '',
        status: 0,
        data: { test: 'vite-plugin-fake-server is working' }
      };
    }
  },

  // 卡片管理接口
  {
    url: '/card_manage/api/cards',
    method: 'get',
    response: ({ query }) => {
      const { _action, _subAction, page, perPage } = query;

      if (_action === 'getData') {
        if (_subAction === 'getCardTypes') {
          // 卡类型选项
          return {
            msg: '',
            status: 0,
            data: [
              { value: 'virtual', label: '虚拟卡', disable: false },
              { value: 'physical', label: '实体卡', disable: false },
              { value: 'prepaid', label: '预付卡', disable: false }
            ]
          };
        } else if (_subAction === 'getCardFormFactors') {
          // 卡介质选项
          return {
            msg: '',
            status: 0,
            data: [
              { value: 'digital', label: '数字卡', disable: false },
              { value: 'physical', label: '实体卡', disable: false },
              { value: 'virtual', label: '虚拟卡', disable: false }
            ]
          };
        } else if (_subAction === 'getCardStatus') {
          // 卡状态选项
          return {
            msg: '',
            status: 0,
            data: [
              { value: 'normal', type: 'success', label: '正常' },
              { value: 'canceling', type: 'warning', label: '注销中' },
              { value: 'cancelled', type: 'danger', label: '已注销' },
              { value: 'frozen', type: 'danger', label: '冻结' }
            ]
          };
        } else if (page && perPage) {
          // 卡片列表数据
          const pageNum = parseInt(page as string, 10);
          const perPageNum = parseInt(perPage as string, 10);
          const start = (pageNum - 1) * perPageNum;
          const end = start + perPageNum;

          // 模拟卡片数据
          const mockCards = Array.from({ length: 50 }, (_, i) => ({
            id: i + 1,
            card_json: {
              cardId: `CARD${String(i + 1).padStart(4, '0')}`,
              maskCardNo: `**** **** **** ${String(i + 1).padStart(4, '0')}`,
              cardNo: `424242424242${String(i + 1).padStart(4, '0')}`,
              firstName: 'John',
              lastName: 'Doe',
              email: 'john.doe@example.com',
              cardFormFactor: i % 3 === 0 ? 'digital' : i % 3 === 1 ? 'physical' : 'virtual',
              cardType: i % 3 === 0 ? 'virtual' : i % 3 === 1 ? 'physical' : 'prepaid',
              nickname: i % 5 === 0 ? 'My Card' : '',
              cardBalance: 1000 + (i * 100),
              cardCurrency: 'USD',
              cardStatus: i % 4 === 0 ? 'normal' : i % 4 === 1 ? 'canceling' : i % 4 === 2 ? 'cancelled' : 'frozen',
              cardScheme: i % 2 === 0 ? 'VISA' : 'MasterCard'
            },
            created_at: `2024-01-${String((i % 28) + 1).padStart(2, '0')}T10:00:00Z`
          }));

          const paginatedCards = mockCards.slice(start, end);

          return {
            msg: '',
            status: 0,
            data: {
              items: paginatedCards,
              total: mockCards.length
            }
          };
        }
      }

      // 默认返回空数据
      return {
        msg: '',
        status: 0,
        data: {}
      };
    }
  },

  // 充值记录接口
  {
    url: '/api/recharges',
    method: 'get',
    response: ({ query }) => {
      const { _action, page = 1, perPage = 10, audit_status } = query;

      if (_action === 'getData') {
        // 模拟充值记录数据
        const mockRecharges = Array.from({ length: 50 }, (_, i) => ({
          id: `RCH${String(i + 1).padStart(4, '0')}`,
          amount: (100 + (i * 50)).toString(),
          money: (100 + (i * 50)).toString(),
          pay_type: i % 3 === 0 ? 'alipay' : i % 3 === 1 ? 'wechat' : 'bank',
          audit_status: i % 4 === 0 ? 'approved' : i % 4 === 1 ? 'pending' : i % 4 === 2 ? 'rejected' : 'pending',
          created_at: `2024-01-${String((i % 28) + 1).padStart(2, '0')}T10:00:00Z`,
          voucher: i % 5 === 0 ? 'https://via.placeholder.com/150' : undefined,
          exchange_rate: '6.5',
          money_cny: ((100 + (i * 50)) * 6.5).toString(),
          audit_reason: i % 10 === 0 ? '资料不完整' : undefined,
          updated_at: `2024-01-${String((i % 28) + 1).padStart(2, '0')}T14:30:00Z`
        }));

        // 根据审核状态过滤
        let filteredRecharges = mockRecharges;
        if (audit_status) {
          filteredRecharges = filteredRecharges.filter(recharge =>
            recharge.audit_status === audit_status
          );
        }

        const pageNum = parseInt(page as string, 10);
        const perPageNum = parseInt(perPage as string, 10);
        const start = (pageNum - 1) * perPageNum;
        const end = start + perPageNum;
        const paginatedRecharges = filteredRecharges.slice(start, end);

        return {
          msg: '',
          status: 0,
          data: {
            items: paginatedRecharges,
            total: filteredRecharges.length
          }
        };
      }

      // 默认返回空数据
      return {
        msg: '',
        status: 0,
        data: {}
      };
    }
  }
]);